import React, { useCallback, useEffect, useState } from 'react';
import { Button, Input, Space, Table, Modal, message, Card, Typography, Layout, Badge } from 'antd';
import type { GetProps } from 'antd';
import http from '../api/http';
import type { Imeals, IEditmeals } from '../types/meals';
import Column from 'antd/lib/table/Column';
import type { PaginationProps, TableProps } from 'antd';
import { 
  DeleteOutlined, 
  ExclamationCircleOutlined, 
  PlusOutlined, 
  EditOutlined,
  FilterOutlined,
  RestOutlined
} from '@ant-design/icons';
import { Add } from './add';
import { Edit } from './edit';
import type { SearchProps } from 'antd/es/input/Search';
import { Divider, Flex, Tag, Tooltip } from 'antd';

const { Search } = Input;
const { confirm } = Modal;
const { Title, Text } = Typography;
const { Content } = Layout;

export default function Meals() {
  // 状态管理
  const [name, setname] = useState('');
  const [data, setdata] = useState<Imeals[]>([]);
  const [pagination, setpagination] = useState({
    page: 1,
    size: 10,
    total: 0
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [EditModalOpen, setEditModalOpen] = useState(false);
  const [currentEditData, setCurrentEditData] = useState<Imeals | undefined>();

  // 数据获取
  const search = useCallback(() => {
    setLoading(true);
    http.getList<Imeals>("Meals/page", {
      page: pagination.page,
      size: pagination.size,
      name: name
    }).then(res => {
      setdata(res.data || []);
      setpagination(n => ({
        ...n,
        page: res.page || n.page,
        total: res.count || 0  
      }));
    }).catch(err => {
      message.error('数据加载失败');
      console.error(err);
    }).finally(() => {
      setLoading(false);
    });
  }, [pagination.page, pagination.size, name]);

  useEffect(() => {
    search();
  }, [name, search]);

  // 搜索处理
  const onSearch: SearchProps['onSearch'] = (value) => {
    setname(value);
    setpagination(prev => ({ ...prev, page: 1 }));
  };

  // 分页处理
  const handleTableChange: PaginationProps['onChange'] = (page, size) => {
    setpagination({ page: page, size: size, total: pagination.total });
  };

  // 刷新数据
  const handleRefresh = () => {
    search();
  };

  // 单行删除
  const handleDelete = (id: number) => {
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除这条膳食记录吗？此操作不可撤销。',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        setLoading(true);
        http.delete("Meals", { id: id })
          .then(() => {
            message.success('删除成功');
            search();
            setSelectedRowKeys([]);
          })
          .catch(err => {
            console.error('删除失败:', err);
            message.error('删除失败');
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的记录');
      return;
    }

    confirm({
      title: '批量删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${selectedRowKeys.length} 条膳食记录吗？此操作不可撤销。`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        setLoading(true);
        http.deleteBatch('Meals/dels', selectedRowKeys)
          .then(() => {
            message.success('批量删除成功');
            search();
            setSelectedRowKeys([]);
          })
          .catch(err => {
            console.error('批量删除失败:', err);
            message.error('批量删除失败');
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  // 行选择配置
  const rowSelection: TableProps<Imeals>['rowSelection'] = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
    ],
  };

  // 模态框控制
  const showModal = () => {
    setIsModalOpen(true);
  };

  const EditShowModal = (record: Imeals) => {
    setCurrentEditData(record);
    setEditModalOpen(true);
  };

  const EditHandleCancel = () => {
    setEditModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 健康标签渲染
  const renderHealthTag = (value: number, label: string) => (
    <Tooltip title={label}>
      {value === 1 ? (
        <Tag color="success" bordered={false}>适宜</Tag>
      ) : (
        <Tag color="error" bordered={false}>不适宜</Tag>
      )}
    </Tooltip>
  );

  return (
    <Layout style={{ minHeight: '100%', padding: '24px' }}>
      <Content>
        <Card 
          title={
            <Flex align="center" gap={8}>
              <Title level={4} style={{ margin: 0 }}>膳食管理</Title>
              <Badge count={pagination.total} size="small" />
            </Flex>
          }
          bordered={false}
          style={{ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)' }}
        >
          {/* 操作栏 */}
          <Flex 
            justify="space-between" 
            align="center" 
            style={{ marginBottom: 16, flexWrap: 'wrap', gap: 8 }}
          >
            <Space>
              <Search
                placeholder="请输入膳食名称"
                onSearch={onSearch}
                style={{ width: 300 }}
                allowClear
                enterButton={<FilterOutlined />}
              />
              <Button 
                icon={<RestOutlined />} 
                onClick={handleRefresh}
                loading={loading}
              >
                刷新
              </Button>
            </Space>

            <Space>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
              >
                批量删除
                {selectedRowKeys.length > 0 && (
                  <Badge count={selectedRowKeys.length} offset={[5, -5]} />
                )}
              </Button>
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={showModal}
              >
                添加膳食
              </Button>
            </Space>
          </Flex>

          {/* 表格内容 */}
          <Table<Imeals>
            dataSource={data}
            rowKey="id"
            pagination={{
              current: pagination.page,
              pageSize: pagination.size,
              total: pagination.total,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条数据`,
              pageSizeOptions: ['10', '20', '50'],
              showSizeChanger: true,
              onChange: handleTableChange,
              align: 'center',
              showSizeChangerTooltips: ['10条/页', '20条/页', '50条/页']
            }}
            rowSelection={rowSelection}
            loading={loading}
            scroll={{ x: 'max-content' }}
            rowClassName={(record, index) => 
              index % 2 === 0 ? 'table-row-even' : 'table-row-odd'
            }
            style={{ 
              borderRadius: '8px', 
              border: '1px solid #f0f0f0',
              transition: 'all 0.3s'
            }}
            onRow={(record) => ({
              onMouseEnter: () => {},
              onMouseLeave: () => {},
              style: {
                transition: 'background-color 0.2s'
              }
            })}
          >
            <Column title="编号" dataIndex="id" key="id" width={80} />
            <Column title="编码" dataIndex="code" key="code" width={100} />
            <Column title="类型" dataIndex="tname" key="tname" width={100} />
            <Column 
              title="膳食名称" 
              dataIndex="name" 
              key="name" 
              width={150}
              render={(text) => <Text ellipsis={{ tooltip: text }}>{text}</Text>}
            />
            <Column title="100g含能量" dataIndex="energy" key="energy" width={120} />
            <Column title="蛋白质含量" dataIndex="protein" key="protein" width={120} />
            <Column title="脂肪含量" dataIndex="fat" key="fat" width={120} />
            <Column title="碳水化合物含量" dataIndex="carbohydrate" key="carbohydrate" width={140} />
            <Column title="每kcal能量" dataIndex="kcal" key="kcal" width={120} />
            <Column title="每kj能量" dataIndex="kj" key="kj" width={120} />
            <Column 
              title="高血压" 
              dataIndex="hbp" 
              key="hbp" 
              width={100}
              render={(hbp) => renderHealthTag(hbp, '高血压适宜性')} 
            />
            <Column 
              title="糖尿病" 
              dataIndex="diabetes" 
              key="diabetes" 
              width={100}
              render={(diabetes) => renderHealthTag(diabetes, '糖尿病适宜性')} 
            />
            <Column 
              title="冠心病" 
              dataIndex="chd" 
              key="chd" 
              width={100}
              render={(chd) => renderHealthTag(chd, '冠心病适宜性')} 
            />
            <Column 
              title="脑卒中" 
              dataIndex="stroke" 
              key="stroke" 
              width={100}
              render={(stroke) => renderHealthTag(stroke, '脑卒中适宜性')} 
            />
            <Column 
              title="心脑血管疾病" 
              dataIndex="cacd" 
              key="cacd" 
              width={140}
              render={(cacd) => renderHealthTag(cacd, '心脑血管疾病适宜性')} 
            />
            <Column 
              title="高血脂" 
              dataIndex="hyperlipidemia" 
              key="hyperlipidemia" 
              width={100}
              render={(hyperlipidemia) => renderHealthTag(hyperlipidemia, '高血脂适宜性')} 
            />
            <Column 
              title="肥胖" 
              dataIndex="obesity" 
              key="obesity" 
              width={100}
              render={(obesity) => renderHealthTag(obesity, '肥胖适宜性')} 
            />
            <Column 
              title="通风" 
              dataIndex="ventilate" 
              key="ventilate" 
              width={100}
              render={(ventilate) => renderHealthTag(ventilate, '通风适宜性')} 
            />
            <Column 
              title="说明" 
              dataIndex="explain" 
              key="explain" 
              width={200}
              render={(text) => <Text ellipsis={{ rows: 2, tooltip: text }}>{text}</Text>}
            />
            <Column
              title="操作"
              key="action"
              width={160}
              fixed="right"
              render={(_, record: Imeals) => (
                <Space size="small">
                  <Button
                    type="primary"
                    size="small"
                    icon={<EditOutlined />}
                    onClick={() => EditShowModal(record)}
                    style={{ padding: '4px 8px' }}
                  >
                    编辑
                  </Button>
                  <Button
                    danger
                    size="small"
                    icon={<DeleteOutlined />}
                    onClick={() => handleDelete(record.id)}
                    style={{ padding: '4px 8px' }}
                  >
                    删除
                  </Button>
                </Space>
              )}
            />
          </Table>
        </Card>

        {/* 模态框组件 */}
        <Add 
          onSuccess={search} 
          isModalOpen={isModalOpen} 
          handleCancel={handleCancel} 
        />
        <Edit 
          onSuccess={search} 
          EditModalOpen={EditModalOpen} 
          EditHandleCancel={EditHandleCancel} 
          editData={currentEditData} 
        />
      </Content>
    </Layout>
  );
}